<?php

namespace app\api\model;

use addons\wechat\library\Config;
use think\Model;

class ShopProduct extends ApiModel
{
    public function freight()
    {
        return $this->belongsTo('ShopFreight','freight_id','id')->field('id,title,freight_price,ceiling_price');
    }

    //获取单个商品
    public static function getById($id)
    {
        $data = self::where('id', $id)
            ->with('freight')
            ->find();
        $res['data'] = empty($data)? [] :$data->toArray();
        $res['comment'] = empty($data)? [] :ShopComment::getList($id);
        return $res;
    }

    //获取多个商品
    public static function getByIds($ids)
    {
        $res = self::where('id','in', $ids)
            ->with('freight')
            ->select();
        !empty($res) && $res = $res->toArray();
        return $res;
    }

    //获取商品分页
    public static function getList($map, $page = 1, $row = 10, $order = [])
    {
        $field = ['id','cat_id','pro_name','pro_image','pro_price','pro_brief','pro_content','sales_count'];
        $sort = [
            'weigh','createtime'=>'desc'
        ];
        $data = self::where($map)
            ->page($page, $row)
            ->field($field)
            ->order(array_merge($sort,$order))
            ->select();
        $res['data'] = empty($data)? [] :$data->toArray();
        $total = self::where($map)->count();
        $res['has_more'] = ceil($total / $row) > $page ? true : false;
        return $res;
    }
    public static function addSaleNum($proId,$num=1)
    {
        self::where('id',$proId)->setInc('sales_count',$num);
    }

    public static function subSaleNum($proId,$num=1)
    {
        self::where('id',$proId)->setDec('sales_count',$num);
    }

    public function getSpecNameAttr($value)
    {
        return explode(',', $value);
    }

    public function getSpecPriceAttr($value)
    {
        $priceArr = explode(',', $value);
        foreach($priceArr as &$price){
            $price = floatval($price);
        }
        return $priceArr;
    }

    public function getProImagesAttr($value)
    {
        return explode(',', $value);
    }
    public function getProSlidesAttr($value)
    {
        return explode(',', $value);
    }
}
